const app = getApp()
const HOST = 'https://www.devbbq.cn'
import { COLOR, SIZE } from '../../common/constant'
import { segmentPortraitPic, detectface } from '../../common/cloud-server'
let headwidth = 0
let headheight = 0
let headX = 0
let headY = 0
Page({
  data: {
    showDialog: false,
    dialogText: '正在为您处理',
    loading: false,
    showSaveBtn: false,
    showPicBox: true,
    // sizeList: SIZE,
    colorList: COLOR,
    pixel: '',
    aPixel: '',
    pointX: 0,// 头像X坐标
    pointY: 0, // 头像Y坐标
    headw: 0,
    picWidth: 0,
    picHeight: 0,
    imgWidth: 0,
    imgHeight: 0,
    previewUrl: '../../static/img/pic.jpg',
    picUrl: '',
    backgroundColor: '',
    ResultImageUrl: ''
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  
  onLoad(options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    const thar = this
    const {picSize, pixel, aPixel, point, headw} = options
    const [width, height] = picSize.split(',')
    const [pointX, pointY] = point.split(',')
    console.log(pointX, pointY);
    this.setData({
      picWidth: +width,
      picHeight: +height,
      pixel, 
      aPixel,
      pointX,
      pointY,
      headw
    })
    this.scalex2(width, height)
    this.createCanvas().then(({canvas, ctx})=>{
      ctx.rect(0, 0, thar.data.picWidth, thar.data.picHeight)
      //创建一个矩形路径。需要用 fill 或者 stroke 方法将矩形真正的画到 canvas 中,这里面的像素大小已经是2倍的了
      ctx.fillStyle = '#cfcfcf'
      ctx.fill()
    })
 
  },

  onReady() {
 
  },
  scalex2(width, height) {
      this.setData({
        imgWidth: width / 2,
        imgHeight: height / 2
      })
  },
  // 选择画布
  selectCanvas() {
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery()
      query.select('#myCanvas').fields({ node: true, size: true})
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          resolve({canvas, ctx})
        })
      })
  },
  
  drawImage({
    filePath,
    isSave = false,
    pw,
    ph,
    px,
    py
  }) {
    return new Promise((resolve, reject) => {
      const thar = this
      this.selectCanvas().then(({ canvas, ctx }) => {
        var img = canvas.createImage()
        img.onload = () => {
          //const bilyu = img.width / img.height // 算出宽高比
          //const ph = thar.data.picWidth / bilyu // 转换成画布宽度
          // if(ph < thar.data.picHeight) { // 如果相片的高度小于画布的高度
          //   ctx.drawImage(img, 0, thar.data.picHeight - ph, thar.data.picWidth, ph)
          // } else {
            ctx.drawImage(img, px, py, pw, ph)
          // }
          isSave && ctx.save()
          resolve()
        }
        img.src = filePath
      })
    })
  },
  // 图片压缩
  wxCompressImage(url) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: url,
        quality: 1,
        success:res =>{
            // 压缩后
       
              resolve(res.tempFilePath)
        }
      })
    })
  },
  openFile() {
    var thar = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      async success (res) {
        const { tempFilePath,size } = res.tempFiles[0]
        thar.setData({ loading: true, showPicBox: false })
        const imgsizeMB =  (size/1024/1024).toFixed(2)
        const compressEmpFilePath =  await thar.wxCompressImage(tempFilePath)  // 压缩后的图片
   
        let wxCdnImg =  new wx.serviceMarket.CDN({
          type: 'filePath',
          filePath: compressEmpFilePath
        })        
        thar.setData({ 
          picUrl: wxCdnImg.options.filePath,
          dialogText: '正在计算头像坐标'
        })
        detectface(wxCdnImg).then((res) => {
          console.log(res);
          const { FaceInfos, ImageHeight, ImageWidth } = res
          const { Width, X, Y } = FaceInfos[0]
          const { picHeight, picWidth } = thar.data // 相框的宽高度

            // 1.计算出一寸头像的大小比例
            const wv = ImageWidth/Width // 图片宽度与头像宽度之比
            let sumw =  thar.data.headw * wv
            if(sumw < picWidth) { // 有的图片缩放之后宽度会小于相框的宽度
              sumw =  sumw + (picWidth - sumw + 10) // 加4个像素的安全距离
              console.log("图片宽度不足,需要放大",sumw)
            }
            const whlv = ImageWidth / ImageHeight
            const sumh = sumw / whlv // 得到图片需要放大或缩小的宽高度sumw, sumh
            console.log(sumh, sumw, 8899 );

            //开始计算坐标 
            const XRatio =  X / ImageWidth
            const YRatio =  Y / ImageHeight
            // 转换后得坐标点
            const XActual = sumw * XRatio
            const YActual = sumh * YRatio
            const Xpic = thar.data.pointX
            const Ypic =  thar.data.pointY
            const XRes = Xpic - XActual// 用一寸相框标记的坐标减去头像标记的坐标等于实际要移动的像素点
            const YRes = Ypic - YActual

            headwidth = parseInt(sumw)
            headheight = parseInt(sumh)
            headX = parseInt(XRes)
            headY = parseInt(YRes)
            
            // if( headwidth < picWidth) {
            //   headwidth = headwidth + (picWidth - headwidth)
            //   console.log('不够宽');
            // }

            // 头像居中处理方法 start========================
            const headOneWidth = sumw / wv // 的得到头像的一寸宽度
            // 1.计算头像居中点
            const headCenterPointX = picWidth / 2 - headOneWidth / 2 - XActual // 一寸长度的一半减去头像的一半，再减去0坐标到头的距离：XActual字段
            headX = headCenterPointX
            console.log(headX, "实际居中点");
            // 头像居中处理方法 end=========================

            // 处理底部白边的问题 start =======================
              // 1.计算原图的底部距离
            const headButtom =  ImageHeight - Y
              // 2.开始转化成缩放后的底部距离 - 参考记录的公式
            const sHeadButtom = headButtom *  sumh / ImageHeight // 缩放后的底部距离
              // 3.加80的安区距离
            const SAFETY = 80
             const headerCount = sHeadButtom + SAFETY // 添加上安区距离的头部到底部的转化后的距离
              if(headerCount < picHeight) { // 如果仍然小于一寸的高度
                headY = headY + (picHeight - headerCount)
                console.log("小于一寸高度，有白边，往下移动"+ (picHeight - headerCount));
              }
            //处理底部白边的问题 end===========================
            thar.setData({
              dialogText: '坐标处理完成'
            })
            console.log('坐标处理完成',res);
            thar.portraitPic(wxCdnImg)
        })
      }
    })
  },
  // 填充背景色
  drawBackground({isSave = true, color = '#cfcfcf'}) {
    const thar = this
    this.selectCanvas().then(({canvas, ctx}) => {
      ctx.rect(0, 0, thar.data.picWidth, thar.data.picHeight) //创建一个矩形路径。需要用 fill 或者 stroke 方法将矩形真正的画到 canvas 中,这里面的像素大小已经是2倍的了
      ctx.fillStyle = color || thar.data.colorList[0].color
      ctx.fill()
      isSave && ctx.save()
      thar.setData({
        previewUrl: canvas.toDataURL()
      })
    })
  },
  portraitPic(wxCdnImg) {
    const thar = this
    this.selectCanvas().then(({ canvas }) => {
      thar.setData({
      dialogText: '正在进行图片处理'
    })
      segmentPortraitPic(wxCdnImg).then((ResultImageUrl) => {
        thar.setData({ 
          ResultImageUrl,
          dialogText: '处理完毕'
         })
        thar.imgBeReady().then(()=>{
          thar.setData({
            showSaveBtn: true,
            loading: false,
            showPicBox: true
          })
        })
      }).catch((err) => {
        if(err === 87014) {
          thar.setData({ 
            dialogText: '照片不符合规范，请重新上传'
           })
           setTimeout(()=>{
            thar.setData({ 
              loading: false,
              showPicBox: true
             })
           },3000)
        }
      })
    })
  },
  imgBeReady() {
    const thar = this
    const { ResultImageUrl } = thar.data
    return new Promise((resolve) => {
      thar.drawBackground({ color: thar.data.backgroundColor })
      if (ResultImageUrl) {
        thar.drawImage({
          filePath: thar.data.ResultImageUrl,
          pw: headwidth,
          ph: headheight,
          px: headX,
          py: headY
        }).then(() => {  
          thar.previewImg()
          resolve()
        })
      }
    })
  },
  // 预览图
  previewImg() {
    const thar = this
    this.selectCanvas().then(({canvas}) => {
      thar.setData({
        previewUrl: canvas.toDataURL()
      })
    })
  },
  imageSave() {
    const thar = this
    this.selectCanvas().then(({canvas, ctx}) => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: thar.data.picWidth,
        height: thar.data.picHeight,
        destWidth: thar.data.picWidth,
        destHeight: thar.data.picHeight,
        canvas,
        success(res) {
          const {
            tempFilePath
          } = res
          // 保存图片到相册
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showToast({
                title: '保存成功',
                mask:true
              })
              setTimeout(()=>{
                thar.setData({
                  showDialog: true
                })
              },1000)
              
              console.log("保存成功", res);
            },
            fail(err) {
              wx.showToast({
                title: '保存失败',
                mask:true
              })
              console.log("保存失败", err);
            }
          })
        }
      })
    })
  }, 
  createCanvas() {
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery()
      query.select('#myCanvas').fields({ node: true, size: true})
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          const dpr = wx.getSystemInfoSync().pixelRatio
          canvas.width = res[0].width * dpr
          canvas.height = res[0].height * dpr
          ctx.scale(dpr, dpr)
          resolve({canvas, ctx})
        })
    })
  },
  // 选择颜色背景
  async colorHandle(e) {
    const { color } = e.mark
    const { ResultImageUrl } = this.data
    this.setData({
      backgroundColor: color,
      showPicBox: !ResultImageUrl
    })
    await this.imgBeReady() // 开始重新画
    this.setData({
      showPicBox: true
    })
  },
  sizeHandle(e) {
    const { size } = e.mark
    const [width, height] = size.split(',')
    const thar = this
    this.scalex2(width, height)
    this.setData({
      picWidth:  +width,
      picHeight:  +height
    })
    this.createCanvas().then(({canvas, ctx})=>{
      ctx.rect(0, 0, thar.data.picWidth, thar.data.picHeight)
      //创建一个矩形路径。需要用 fill 或者 stroke 方法将矩形真正的画到 canvas 中,这里面的像素大小已经是2倍的了
      ctx.fillStyle = '#cfcfcf'
      ctx.fill()
    })
  },
  onShareAppMessage() {
    return {
      title: '免费制作您的证件照',
      path: '/pages/home/index',
      imageUrl: '../../static/img/pic.jpg'
    }
  }
})